﻿using System;
using BlazorDownloadFile;
using BootstrapBlazor.Components;
using iTeamyou.LTS.Core.Models;
using iTeamyou.LTS.Core.Services;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;
using iTeamyou.LTS.UI.Utils;
using Microsoft.AspNetCore.Components.Forms;
using System.ComponentModel;
using iTeamyou.LTS.UI.Models;

namespace iTeamyou.LTS.UI.Pages.Archive.Manufacturer
{
    public partial class LicenseComponent
    {
        [Inject]
        [NotNull]
        private DialogService? DialogService { get; set; }

        [Inject]
        [NotNull]
        private MessageService? MessageService { get; set; }
        [Inject] ToastService Toast { get; set; }

        [Inject] ManufacturerService? ManufacturerService { get; set; }
        [Inject] SharedService? SharedService { get; set; }
        [Inject] ManufacturerAttachmentService? attachmentService { get; set; }
        [Inject] IBlazorDownloadFileService BlazorDownloadFileService { get; set; }
        [Inject] static IFileService<ManufacturerLicense, string, string>? FileService { get; set; } = new AliManufacturerLicenseService();

        [Parameter]
        public Action? OnClose { get; set; }

        [Parameter]
        public string LicenseId { get; set; }

        [Parameter]
        public string UserId { get; set; }

        [Parameter]
        public EventCallback<Core.Models.Manufacturer> OnLicenseSaved { get; set; }

        //新建或编辑
        [Parameter]
        public DocStatus DocStatus { get; set; }
        public bool IsButtonDisabled { get; set; }
        public bool IsDeleteDisabled { get; set; }
        public bool IsFieldReadOnly { get; set; }

        public string deleteMessage { get; set; }

        [Parameter]
        public Core.Models.Manufacturer? Manufacturer { get; set; }

        [Parameter]
        public ManufacturerLicense? LicenseModel { get; set; }

        private List<UploadFile> LicenseFile { get; set; }
        private List<UploadFile> OtherFile { get; set; }

        public List<SelectedItem>? ManufacturerLicenseTypeList { get; set; }

        private List<string> PreviewList { get; set; } = new() { "-" };

        [NotNull]
        private ImagePreviewer? ImagePreviewer { get; set; }

        private long MaxFileLength;
        private int MaxFileLengthMB;
        private string? ResourcePath;
        private string? ResourceURL;
        private string? RootURL;
        private string UploadType;
        private string PreviewUrl;

        protected override async void OnInitialized()
        {
            PageOpInit();
            LicenseFile = new List<UploadFile>();
            OtherFile = new List<UploadFile>();
            deleteMessage = GetDeleteMessage();
            ResourcePath = SharedService.GetConfig("ResourcePath");
            ResourceURL = SharedService.GetConfig("ResourceURL");
            RootURL = SharedService.GetConfig("RootURL");
            MaxFileLengthMB = int.Parse(SharedService.GetConfig("MaxUploadSize"));
            MaxFileLength = MaxFileLengthMB * 1024 * 1024;

            if (LicenseModel == null)
                LicenseModel = new ManufacturerLicense() { Name = "-" };
            else
                await OnAttachmentInit();

            GetLicenseTypes();
            base.OnInitialized();
        }

        protected override void OnParametersSet()
        {
            base.OnParametersSet();
        }

        private void PageOpInit()
        {
            switch (DocStatus)
            {
                case DocStatus.New:
                    IsButtonDisabled = false;
                    IsFieldReadOnly = false;
                    IsDeleteDisabled = true;
                    break;
                case DocStatus.Edit:
                    IsButtonDisabled = false;
                    IsFieldReadOnly = false;
                    IsDeleteDisabled = false;
                    break;
                case DocStatus.Archive:
                    IsButtonDisabled = true;
                    IsFieldReadOnly = true;
                    IsDeleteDisabled = true;
                    break;
                case DocStatus.View:
                    IsButtonDisabled = true;
                    IsFieldReadOnly = true;
                    IsDeleteDisabled = true;
                    break;
                default:
                    break;
            }
        }

        private async Task ShowPreviewer()
        {
            if (UploadType.Contains("image"))
                ImagePreviewer.Show();
            else if (UploadType.Contains("pdf"))
            {
                var op = new DialogOption()
                {
                    Title = "证照预览",
                    ShowFooter = false
                };
                op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<PDFComponent>(new Dictionary<string, object?>
                {
                    [nameof(PDFComponent.PreviewUrl)] = PreviewUrl
                }).Render();
                op.IsScrolling = true;
                await DialogService.Show(op);
            }
        }

        private async Task OnAttachmentInit()
        {
            //绑定解除后无法获取关联附件信息到model中
            var attachment = new ManufacturerLicenseAttachment();
            var otherAttachments = new List<ManufacturerLicenseAttachment>();
            if (LicenseModel.Attachments == null)
            {
                LicenseModel.Attachments = new List<ManufacturerLicenseAttachment>();
                attachment = attachmentService.GetList(LicenseModel.Id, true).FirstOrDefault();
                otherAttachments = attachmentService.GetList(LicenseModel.Id, false).ToList();
                if (attachment != null)
                {
                    LicenseModel.Attachments.Add(attachment);
                    var file = new UploadFile()
                    {
                        FileName = attachment.Name,
                        //PrevUrl = "data:" + attachment.ContentType + ";base64," + attachment.FileContent,
                        Size = attachment.FileSize
                    };

                    //LicenseFile.Add(file);
                    //UploadType = attachment.ContentType;
                    //PreviewList = new List<string> { attachment.URL };
                    //PreviewUrl = attachment.URL.Replace(RootURL, "");

                    UploadType = attachment.ContentType;
                    if (UploadType.Contains("image"))
                    {
                        PreviewList = new List<string> { attachment.URL };
                        using FileStream fs = new(attachment.Path, FileMode.Open, FileAccess.Read);
                        using BinaryReader br = new(fs);
                        byte[] bytes = br.ReadBytes((int)fs.Length);
                        var fileContent = Convert.ToBase64String(bytes);
                        file.PrevUrl = "data:" + attachment.ContentType + ";base64," + fileContent;
                    }
                    else if (UploadType.Contains("pdf"))
                        PreviewUrl = attachment.URL.Replace(RootURL, "");

                    LicenseFile.Add(file);
                }
                if (otherAttachments.Any())
                {
                    LicenseModel.Attachments.AddRange(otherAttachments);
                    foreach (var other in otherAttachments)
                    {
                        var file = new UploadFile()
                        {
                            FileName = other.Name,
                            Size = other.FileSize,
                            //PrevUrl = "data:" + other.ContentType + ";base64," + other.FileContent
                        };
                        OtherFile.Add(file);
                    }
                }
            }
            else
            {
                attachment = LicenseModel.Attachments.Where(a => a.IsMain == true).FirstOrDefault();
                otherAttachments = LicenseModel.Attachments.Where(a => a.IsMain == false).ToList();
                if (attachment != null)
                {
                    var file = new UploadFile()
                    {
                        FileName = attachment.Name,
                        //PrevUrl = "data:" + attachment.ContentType + ";base64," + attachment.FileContent,
                        Size = attachment.FileSize
                    };

                    //LicenseFile.Add(file);
                    //UploadType = attachment.ContentType;
                    //PreviewList = new List<string> { attachment.URL };
                    //PreviewUrl = attachment.URL.Replace(RootURL, "");

                    UploadType = attachment.ContentType;
                    if (UploadType.Contains("image"))
                    {
                        PreviewList = new List<string> { attachment.URL };
                        using FileStream fs = new(attachment.Path, FileMode.Open, FileAccess.Read);
                        using BinaryReader br = new(fs);
                        byte[] bytes = br.ReadBytes((int)fs.Length);
                        var fileContent = Convert.ToBase64String(bytes);
                        file.PrevUrl = "data:" + attachment.ContentType + ";base64," + fileContent;
                    }
                    else if (UploadType.Contains("pdf"))
                        PreviewUrl = attachment.URL.Replace(RootURL, "");

                    LicenseFile.Add(file);
                }
                if (otherAttachments.Any())
                {
                    foreach (var other in otherAttachments)
                    {
                        var file = new UploadFile()
                        {
                            FileName = other.Name,
                            Size = other.FileSize,
                            //PrevUrl = "data:" + other.ContentType + ";base64," + other.FileContent
                        };
                        OtherFile.Add(file);
                    }
                }
            }
            StateHasChanged();
        }

        private async Task OnValidSubmit(EditContext model)
        {
            var exist = ManufacturerService.Get(LicenseModel.LId);
            if (exist != null && DocStatus == DocStatus.New)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = $"证照保存失败，原因：相同的证照编号已存在",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
                return;
            }

            if (LicenseFile == null || !LicenseFile.Any())
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = $"证照保存失败，原因：证照必须上传附件",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
                return;
            }

            LicenseModel.ManufacturerId = Manufacturer.Id;
            LicenseModel.ManufacturerName = Manufacturer.Name;
            LicenseModel.LastModifiedBy = UserId;
            LicenseModel.LastModifiedOn = DateTime.Now;

            if (DocStatus == DocStatus.New)
            {
                //LicenseModel.Id = Guid.NewGuid().ToString("N");
                LicenseModel.CreatedBy = UserId;
                LicenseModel.CreatedOn = DateTime.Now;
                //LicenseModel.Id = Guid.NewGuid().ToString("N");
                //var licenses = new List<ManufacturerLicense>
                //{
                //    LicenseModel
                //};
                //Manufacturer.ManufacturerLicenses = licenses;
                Manufacturer.ManufacturerLicenses.Add(LicenseModel);
            }
            else
            {
                //Manufacturer.ManufacturerLicenses = ManufacturerService.GetLicensesById(Manufacturer.Id);
                var exists = Manufacturer.ManufacturerLicenses.Where(s => s.Id == LicenseModel.Id);
                if (exists != null && exists.Any())
                    Manufacturer.ManufacturerLicenses.Remove(exists.FirstOrDefault());
                Manufacturer.ManufacturerLicenses.Add(LicenseModel);
            }

            //ManufacturerService.Save(Manufacturer);
            StateHasChanged();
            await OnLicenseSaved.InvokeAsync(Manufacturer);
            SharedService.CallRequestRefresh();
            await Task.CompletedTask;
            OnClose?.Invoke();
            await MessageService.Show(new MessageOption()
            {
                Content = "保存成功",
                Icon = "fa-solid fa-circle-info",
                Color = Color.Success,
                ShowDismiss = true
            });
        }

        private async Task OnInvalidSubmit(EditContext context)
        {
            await MessageService.Show(new MessageOption()
            {
                Content = $"保存失败，字段验证未通过",
                Icon = "fa-solid fa-circle-error",
                Color = Color.Danger,
                ShowDismiss = true
            });
            return;
        }

        private async Task DeleteLicense(ManufacturerLicense license)
        {
            var opTarget = Manufacturer.ManufacturerLicenses.Where(l => l.Id == license.Id).FirstOrDefault();
            if (opTarget.OperationType == 0)
                Manufacturer.ManufacturerLicenses.Remove(license);
            else
                opTarget.OperationType = LicenseOp.Delete;
            //ManufacturerService.Save(Manufacturer);
            StateHasChanged();
            SharedService.CallRequestRefresh();
            await Task.CompletedTask;
            OnClose?.Invoke();
            await MessageService.Show(new MessageOption()
            {
                Content = "删除证照成功",
                Icon = "fa-solid fa-circle-info",
                Color = Color.Success,
                ShowDismiss = true
            });
        }

        private async Task OnLicenseFileChange(UploadFile file)
        {
            if (file != null && file.File != null)
            {
                // 服务器端验证当文件大于 MaxFileLengthMB 时提示文件太大信息
                if (file.Size > MaxFileLength)
                {
                    await MessageService.Show(new MessageOption()
                    {
                        Content = $"证照上传失败，原因：上传文件不能大于 {MaxFileLengthMB} MB",
                        Icon = "fa-solid fa-circle-error",
                        Color = Color.Danger,
                        ShowDismiss = true
                    });
                    LicenseFile = new List<UploadFile>();
                    return;
                }
                else if (LicenseModel.Type == null)
                {
                    await MessageService.Show(new MessageOption()
                    {
                        Content = $"请先选择证照类型",
                        Icon = "fa-solid fa-circle-error",
                        Color = Color.Danger,
                        ShowDismiss = true
                    });
                    LicenseFile = new List<UploadFile>();
                    return;
                }
                else
                {
                    var newId = Guid.NewGuid().ToString("N");
                    var fileExtension = Path.GetExtension(file.OriginFileName);
                    var fileName = newId + fileExtension;
                    var tempFileName = newId + "_Temp" + fileExtension;
                    var fullFileName = Path.Combine(ResourcePath, fileName);
                    var fullTempFileName = Path.Combine(ResourcePath, tempFileName);
                    await file.SaveToFileAsync(fullFileName, MaxFileLength);
                    await file.SaveToFileAsync(fullTempFileName, MaxFileLength);
                    file.FileName = file.OriginFileName;
                    //var fileContent = "";
                    int fileLength = 0;

                    using (FileStream fs = new FileStream(fullTempFileName, FileMode.Open, FileAccess.Read))
                    {
                        fileLength = (int)fs.Length;
                        if (file.File.ContentType.Contains("image"))
                        {
                            using BinaryReader br = new(fs);
                            byte[] bytes = br.ReadBytes((int)fs.Length);
                            var fileContent = Convert.ToBase64String(bytes);
                            file.PrevUrl = "data:" + file.File.ContentType + ";base64," + fileContent;
                        }
                        //using BinaryReader br = new BinaryReader(fs);
                        //byte[] bytes = br.ReadBytes((int)fs.Length);
                        //fileContent = Convert.ToBase64String(bytes);
                        //fileLength = (int)fs.Length;
                        //file.PrevUrl = "data:" + file.File.ContentType + ";base64," + fileContent;
                        LicenseFile.Add(file);
                    }

                    var attachmentURL = ResourceURL + fileName;

                    var license = FileService.Get(fullFileName, LicenseModel.Type).Result;
                    var attachment = new ManufacturerLicenseAttachment()
                    {
                        Id = newId,
                        Name = file.OriginFileName,
                        Path = fullFileName,
                        ContentType = file.File.ContentType,
                        //FileContent = fileContent,
                        FileSize = fileLength,
                        IsMain = true,
                        URL = attachmentURL
                    };
                    if (license != null)
                    {
                        if (string.IsNullOrEmpty(LicenseModel.LId))
                            LicenseModel.LId = license.LId;

                        if (license.ValidFromDate != null)
                            LicenseModel.ValidFromDate = license.ValidFromDate;

                        if (license.ValidToDate != null)
                            LicenseModel.ValidToDate = license.ValidToDate;
                        //LicenseModel.Attachment = fullFileName;
                        //LicenseModel.AttachmentURL = attachmentURL;
                        LicenseModel.Attachments = new List<ManufacturerLicenseAttachment>() { attachment };
                    }

                    UploadType = attachment.ContentType;
                    if (UploadType.Contains("image"))
                        PreviewList = new List<string> { attachment.URL };
                    else if (UploadType.Contains("pdf"))
                        PreviewUrl = attachment.URL.Replace(RootURL, "");

                    StateHasChanged();
                    await Task.FromResult(true);
                }
            }
        }

        private async Task OnOtherFileChange(UploadFile file)
        {
            if (file != null && file.File != null)
            {
                // 服务器端验证当文件大于 MaxFileLengthMB 时提示文件太大信息
                if (file.Size > MaxFileLength)
                {
                    await MessageService.Show(new MessageOption()
                    {
                        Content = $"证照上传失败，原因：上传文件不能大于 {MaxFileLengthMB} MB",
                        Icon = "fa-solid fa-circle-error",
                        Color = Color.Danger,
                        ShowDismiss = true
                    });
                    //Base64FormatFile = new List<UploadFile>();
                    return;
                }
                else
                {
                    var newId = Guid.NewGuid().ToString("N");
                    var fileExtension = Path.GetExtension(file.OriginFileName);
                    var fileName = newId + fileExtension;
                    var tempFileName = "Temp_" + fileName;

                    var fullFileName = Path.Combine(ResourcePath, fileName);
                    var fullTempFileName = Path.Combine(ResourcePath, tempFileName);

                    await file.SaveToFileAsync(fullFileName, MaxFileLength);
                    await file.SaveToFileAsync(fullTempFileName, MaxFileLength);
                    file.FileName = file.OriginFileName;

                    //var fileContent = "";
                    int fileLength = 0;

                    using (FileStream fs = new FileStream(fullTempFileName, FileMode.Open, FileAccess.Read))
                    {
                        //using BinaryReader br = new BinaryReader(fs);
                        //byte[] bytes = br.ReadBytes((int)fs.Length);
                        //fileContent = Convert.ToBase64String(bytes);
                        fileLength = (int)fs.Length;
                        //file.PrevUrl = "data:" + file.File.ContentType + ";base64," + fileContent;
                    }
                    var attachmentURL = ResourceURL + fileName;
                    //LicenseModel.OtherAttachmentURL = attachmentURL;

                    var attachment = new ManufacturerLicenseAttachment()
                    {
                        Id = newId,
                        Name = file.OriginFileName,
                        Path = fullFileName,
                        ContentType = file.File.ContentType,
                        //FileContent = fileContent,
                        FileSize = fileLength,
                        IsMain = false,
                        URL = attachmentURL
                    };
                    if (LicenseModel.Attachments == null)
                    {
                        LicenseModel.Attachments = new List<ManufacturerLicenseAttachment>();
                    }
                    LicenseModel.Attachments.Add(attachment);
                    StateHasChanged();
                    await Task.FromResult(true);
                }
            }
        }

        //private async Task<bool> OnLicenseFileDelete(UploadFile file)
        //{
        //    var newLicense = new Core.Models.SupplierLicense();
        //    LicenseModel = newLicense;
        //    var newLicenses = new List<Core.Models.License>() { newLicense };
        //    Licenses = newLicenses;
        //    Base64FormatFile.Clear();
        //    StateHasChanged();
        //    return await Task.FromResult(true);
        //}

        //private async Task<bool> OnOtherFileDelete(UploadFile file)
        //{
        //    var download = LicenseModel.Attachments.Where(f => f.Name == file.FileName).FirstOrDefault();
        //    if (download != null)
        //    {
        //        LicenseModel.Attachments.Remove(download);

        //        if (LicenseModel.Attachments.Where(a => a.IsMain == false).Count() == 0)
        //            LicenseModel.OtherAttachmentURL = string.Empty;

        //        StateHasChanged();
        //    }
        //    return await Task.FromResult(true);
        //}

        private async Task OnDownload(UploadFile file)
        {
            var download = LicenseModel.Attachments.Where(f => f.Name == file.FileName).FirstOrDefault();
            if (download != null)
            {
                //BlazorDownloadFileService.DownloadFile(download.Name, download.FileContent, download.ContentType);
                using FileStream fs = new(download.Path, FileMode.Open, FileAccess.Read);
                BlazorDownloadFileService.DownloadFile(download.Name, fs, download.ContentType);
            }
            await Toast.Success("文件下载", $"下载 {file.FileName} 成功");
        }

        private string GetDeleteMessage()
        {
            return $"你确认要证照记录吗";
        }

        private void GetLicenseTypes()
        {
            var licenseTypes = ManufacturerService.GetLicenseType("manufacturer");
            if (licenseTypes != null && licenseTypes.Any())
            {
                ManufacturerLicenseTypeList = new List<SelectedItem>();
                foreach (var type in licenseTypes)
                {
                    ManufacturerLicenseTypeList.Add(new SelectedItem() { Text = type.TypeName, Value = type.TypeId });
                }
            }
        }
    }
}